<template>
  <a-modal v-model:open="open" title="编辑账号" @ok="handleOk" @cancel="handleCancel">
    <a-form ref="formRef" :model="formState" style="margin-top: 16px">
      <a-form-item name="role_name" :rules="[{ required: true, message: '请输入角色名称' }]">
        <a-input v-model:value="formState.role_name" placeholder="请输入角色名称" />
      </a-form-item>
      <a-form-item name="desc">
        <a-textarea v-model:value="formState.desc" placeholder="请输入描述" />
      </a-form-item>
      <a-form-item name="menu_ids">
        <a-tree
          v-model:checkedKeys="formState.menu_ids"
          :field-names="fieldNames"
          checkable
          :tree-data="roleMenus"
        >
        </a-tree>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { createOrUpdateRole, fetchRoleMenus, fetchRoleDetails } from '@/api/system'

const emits = defineEmits(['refresh'])

const open = ref(false)
const handleOk = () => {
  formRef.value.validate().then(async () => {
    console.log(formState.value)
    await createOrUpdateRole(formState.value)
    emits('refresh')
    open.value = false
  })
}
const handleCancel = () => {
  Object.keys(formState.value).forEach(key => {
    formState.value[key] = undefined
  })
  formState.value.menu_ids = []
  open.value = false
}
const openModal = (record: any) => {
  if (record) {
    Object.keys(formState.value).forEach(key => {
      formState.value[key] = record[key]
    })
    formState.value.desc = record.describe_str
    getRoleDetails(record.id)
  }
  if (!roleMenus.value.length) getRoleMenus()
  open.value = true
}

const roleMenus = ref<any>([])
const fieldNames = {
  children: 'children',
  title: 'label',
  key: 'menu_id'
}
const getRoleMenus = async () => {
  const res = await fetchRoleMenus({})
  roleMenus.value = res.data.data
  console.log(roleMenus)
}
const getRoleDetails = async (id: string) => {
  const res = await fetchRoleDetails({ id })
  formState.value.menu_ids = res.data.data.role_menu_ids
}

const formRef = ref()
const formState = ref<any>({
  id: undefined,
  desc: undefined,
  menu_ids: undefined,
  role_name: undefined
})

defineExpose({ openModal })
</script>

<style scoped lang="scss"></style>
